from flask import views, render_template, request, url_for, \
    redirect, Blueprint, make_response
import json
import urllib.request
from mysql_config import db
from models import ItemState
from models import Location
from models import Car
from result import Result
from result_code import Code

moni = Blueprint('moni', __name__)


@moni.route('/state', methods=['POST'])
def update_state():
    oid = request.json.get("oid")
    temp = request.json.get("temp")
    hum = request.json.get("hum")
    res = ItemState.query.filter(ItemState.order_id == oid).first()
    if res is None:  # 查不到则新建
        state = ItemState(order_id=oid, i_temp=temp, i_hum=hum)
        db.session.add(state)
        db.session.commit()
        return vars(Result(Code.UPDATE_OK.value, None, "更新成功"))
    else:
        res.i_temp = temp
        res.i_hum = hum
        db.session.commit()
        return vars(Result(Code.UPDATE_OK.value, None, "更新成功"))


@moni.route('/state/<oid>', methods=['GET'])
def get_state(oid):
    res = ItemState.query.filter(ItemState.order_id == oid).first()
    print(f'结果：{res}')
    if res is None:
        return vars(Result(Code.GET_ERR.value, None, "查询失败"))
    else:
        res_dic = vars(res)
        del res_dic['_sa_instance_state']
        print(f'数据：{res_dic}')
        return vars(Result(Code.GET_ERR.value, res_dic, "查询成功"))


@moni.route('/position', methods=['POST'])
def update_position():
    oid = request.json.get("oid")
    pt = request.json.get("pt")

    if pt == '-1':
        return {Code.GET_ERR.value, None, "经纬度转换失败"}
    # 进行地理逆编码
    key = '78019793b012a9c6b8e361aa55f9282c'
    url = 'https://restapi.amap.com/v3/geocode/regeo?key='
    url += key + '&location=' + pt
    response = urllib.request.urlopen(url).read()
    res_dic = json.loads(response)
    status = res_dic['status']
    if status == 0:
        return {Code.GET_ERR.value, None, "经纬度转换失败"}
    loc = res_dic['regeocode']['formatted_address']
    street = res_dic['regeocode']['addressComponent']['streetNumber']['number']
    loc += street
    if loc is []:
        return {Code.GET_ERR.value, None, "经纬度转换失败"}

    res = Location.query.filter(Location.order_id == oid).first()
    if res is None:
        state = Location(loc=loc, point=pt)
        db.session.add(state)
        db.session.commit()
        return vars(Result(Code.UPDATE_OK.value, None, "更新成功"))
    else:
        res.loc = loc
        res.point = pt
        db.session.commit()
        return vars(Result(Code.UPDATE_OK.value, None, "更新成功"))


@moni.route('/position/<int:oid>', methods=['GET'])
def get_position(oid):
    print(f'oid: {oid}, type: {type(oid)}')
    res = Location.query.filter(Location.order_id == oid).first()
    if res is None:
        return vars(Result(Code.GET_ERR.value, None, "查询失败"))
    else:
        res_dic = vars(res)
        del res_dic['_sa_instance_state']
        print(res_dic)
        return vars(Result(Code.GET_ERR.value, res_dic, "查询成功"))


@moni.route('/car/<cid>', methods=['GET'])
def get_car_data(cid):
    res = Car.query.filter(Location.order_id == cid).first()
    if res is None:
        return vars(Result(Code.GET_ERR.value, None, "查询失败"))
    else:
        res_dic = vars(res)
        del res_dic['_sa_instance_state']
        print(res_dic)
        return vars(Result(Code.GET_ERR.value, res_dic, "查询成功"))



